package com.zhang.zxx.boot.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.zhang.zxx.boot.common.annotate.Log;
import com.zhang.zxx.boot.common.base.Response;
import com.zhang.zxx.boot.common.core.event.LogEvent;
import com.zhang.zxx.boot.common.core.listener.MyEventListener;
import com.zhang.zxx.boot.domain.dto.GeneratorDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.util.Collections;

/**
 * TestController:测试接口
 *
 * @author zhangxiaoxiang
 * @date 2021/11/21
 */
@Api(tags = "测试模块")
@RestController
@RequestMapping("/test")
@Slf4j
@RequiredArgsConstructor
public class TestController {


    private final MyEventListener eventListener;


    @Log
    @ApiOperation(value = "发布事件示例")
    @GetMapping("/pushevent")
    public Response<String> pushEvent(@RequestParam String param) {
        LogEvent builder = LogEvent.builder(param, param + ",你好呀!");
        eventListener.logEvent(builder);
        return Response.data(JSONUtil.toJsonStr(builder));
    }

    @ApiOperation(value = "数据库表生成")
    @GetMapping("/generator")
    public ResponseEntity<String> generator(@Validated GeneratorDTO dto) {
        if (StrUtil.isBlank(dto.getOutputDir())) {
            // dto.setOutputDir(System.getProperty("user.dir") + "/src/main/java")
            dto.setOutputDir("C:\\Users\\zxx\\Desktop\\generator");
            File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
            String desktopPath = desktopDir.getAbsolutePath();
            dto.setOutputDir(desktopPath + "/generator");
        }
        if (StrUtil.isBlank(dto.getOutputXmlDir())) {
            dto.setOutputXmlDir(System.getProperty("user.dir") + "/src/main/resources/mapper/");
        }

        FastAutoGenerator.create(dto.getUrl(), dto.getUsername(), dto.getPassword())
                .globalConfig(builder -> {
                    builder.author(dto.getAuthor()) // 设置作者
                            .enableSwagger() // 开启 swagger 模式
                            // .fileOverride() // 放开注释覆盖已生成文件,注意操作
                            .dateType(DateType.ONLY_DATE)// 只使用 java.util.date 代替
                            .outputDir(dto.getOutputDir()); // 指定输出目录[动态]
                })
                // 设置包名
                .packageConfig(builder -> {
                    builder.parent(dto.getPackageParent())
                            .entity("entity.DO")
                            .service("service")
                            .serviceImpl("service.impl")
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml, dto.getOutputXmlDir())); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude(dto.getAddInclude()) // 设置需要生成的表名
                            // .addTablePrefix("t_", "c_")
                            .entityBuilder().enableLombok()
                            .enableChainModel()
                            .mapperBuilder().enableMapperAnnotation()
                            .mapperBuilder().formatMapperFileName("%sMapper")
                            .mapperBuilder().formatXmlFileName("%sMapper")
                            .serviceBuilder().formatServiceFileName("%sService")
                            .serviceBuilder().formatServiceImplFileName("%sServiceImpl")
                            .controllerBuilder().enableRestStyle().formatFileName("%sController")
                    ; // 设置过滤表前缀
                })

                // 使用Freemarker引擎模板，默认的是Velocity引擎模板,如果不适应自定义就注释掉下面
                .templateEngine(new FreemarkerTemplateEngine())
                .templateConfig((builder) -> builder
                        .entity("templates/mp/entity.java")
                        .mapper("templates/mp/mapper.java")
                        .mapperXml("templates/mp/mapper.xml")
                        .service("templates/mp/service.java")
                        .serviceImpl("templates/mp/serviceImpl.java")
                        .controller("templates/mp/controller.java"))
                .execute();
        log.warn("请在时间字段加上相关注解[空了调试一下模板]\n{}\n{}", "@DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")", " @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")");
        return ResponseEntity.ok(dto.getAddInclude() + "生成成功!");
    }
}
